<?php


namespace PKApp\Install\Classes;


use PKFrame\DataHandler\Arrays;
use PKFrame\Lib\DataBase;
use PKFrame\Service;

class InstallService extends Service
{

    public function CheckDriverByMySQL($params)
    {
        $this->db()->checkDataBaseParamsConfig($params, 'MySQL');
        $this->db()->checkDriverByMySQL($params);
    }

    /**
     * 检查数据库名是否已经存在
     * @param string $name
     * @return bool (true is exists)
     */
    public function GetIsExistsByDB(string $name): bool
    {
        $name = trim($name);
        !empty($name) ?: $this->noticeByJson('db_name_empty');
        $sql_str = $this->db()->SetSql([
            $this->GetSQLFile('mysql.db.exists', 'db_name', $name)
        ])->First();
        return is_array($sql_str);
    }

    public function InstallByCreateDB($name)
    {
        $this->db()->SetSql([
            $this->GetSQLFile('mysql.db.create', 'db_name', $name)
        ])->Exec();
    }

    public function InstallByCreateTable($name)
    {
        $this->db()->SetDBLink()->SetSql([
            $this->GetSQLFile('mysql.db.system',
                [
                    '[db_name]',
                ], [$name])
        ])->Exec();
    }

    public function Upgrade($file_path)
    {
        $config = $this->db()->GetNowConfig();
        $sql_str = fileHelper()->GetContentsByDisk($file_path);
        !empty($sql_str) ?: $this->noticeByJson('SQL execution statement not read, path:' . $file_path);
        $this->db()->BatchRun(str_replace(
            [
                '[db_name]',
            ],
            [
                $config['name'],
            ], $sql_str));
    }

    public function InstallByImportData()
    {
        $list_file = fileHelper()->OpenFolder($this->path_sql . 'Data', 'sql');
        if (Arrays::Is($list_file)) {
            $list_sql = [];
            foreach ($list_file as $item) {
                $list_sql[] = fileHelper()->GetContentsByDisk(urldecode($item['file_path']), 'db_sqlFile_empty');
            }
            $this->db()->SetDBLink()->SetSql($list_sql)->BatchRun();
        }
    }

    public function interface_getEntityById($id, $viewField = '*')
    {
    }

    public function db(): DataBase
    {
        static $cls;
        return empty($cls) ? $cls = new DataBase() : $cls;
    }

    public function GetList($viewParams = [], $viewField = '*')
    {
    }

    public function GetEntity($viewParams = [], $viewField = '*')
    {
    }
}